ES6 相關筆記


Posted by yunanpan on 2020-07-14

宣告變數的新選擇:let 與 const

  • varfunction 為作用域:
function test() {
  if (10 > 5) {
    let a = 10
  }
  console.log(a)
}

test() // 10
  • letconstblock 為作用域:
    變數 a 只生存在 if 裡,所以在 if 外印出的 a 會是 not defined
function test() {
  if (10 > 5) {
    let a = 10
  }
  console.log(a)
}

test() // a is not defined

解構賦值 Destructuring assignment

陣列解構

過去要拿陣列中的值時,要一個一個去宣告:

const arr = [1, 2, 3, 4]
const first = arr[0]
.
.
.
const fourth = arr[3]

但解構賦值可以把陣列或物件中的資料解開擷取成為獨立變數:

const arr = [1, 2, 3, 4]
// first, second, third, fourth 可以分別對應到 arr[0]~arr[3]
var [first, second, third, fourth] = arr
console.log(second, third) // 2 3

因為會照順序對應到陣列裡的元素,如果想要跳過其中的元素,可不輸入對應的變數即可:

const arr = [1, 2, 3, 4]
// 忽略 arr[2] 的情況
var [first, second, , fourth] = arr
console.log(fourth) // 4

也可以設定預設值,在相對應的陣列元素沒有值的時候可以使用:

let first, second;

[first=1, second=2] = [3];
console.log(first); // 3
console.log(second); // 2

也可應用於變數交換

let first = 1
let second = 2
[first, second] = [second, first]
console.log(first, second) // 2 1

物件解構

物件解構可以較方便拿取物件裡的變數。

const obj = {
  name: 'nick',
  age: 30
}
// key 要與對應的物件相同才可以
var {name, age} = obj
console.log(name) // nick
// 如果 key 隨便設會拿不到值
var {hey} = obj
console.log(hey) // undefined

更多方法可參考:
MDN Destructuring assignment


展開

陣列展開

var arr = [1, 2, 3]
var arr2 = [4, 5, 6, ...arr]
console.log(arr2) // [4, 5, 6, 1, 2, 3]

物件展開

var obj1 = {
  a: 1,
  b: 2
}
var obj2 = {
  ...obj1,
  c: 3
}
console.log(obj2) // {a: 1, b: 2, c: 3}

展開的好處可以複製陣列、物件的內容。在之前寫的從物件理解變數 / Immutable 觀念整理中,有提到如果用var arr2 = arr 就像是 arr2arr 一起用同個魚缸養魚,所以更動 arr2 就會動到 arr。但如果用 var arr2 = [...arr] 就等於是複製成新的陣列,即便更動 arr2 也不會影響 arr


反向的展開

(通常會搭配解構使用)

var arr = [1, 2, 3, 4]
// ...rest 只能放在最後面,不然會跳錯
var [first, ...rest] = arr
console.log(rest) // [2, 3, 4]

常使用在可能有多個參數要傳入的 function 中:

function add(...args) {
  console.log(args)
}
add(1, 2) // [1, 2]

預設值 Default Parameters

function repeat(str = 'hello', times = 5) {
  return str.repeat(times)
}
// 當沒輸入參數時,就會照預設值產出結果
console.log(repeat()) // hellohellohellohellohello

箭頭函式

先複習一下常使用的 function 寫法:

function test(n) {
  return n
}
const test = function (n) {
  return n
}

箭頭函式可省略些有的沒的,提高可讀性:

const test = (n) => {
  return n
}
// 如果只有一個參數,可省略 ()
// 如果 {} 裡只有一行可省略 {} 和 return
const test = n => n

ES6 中的 import & export 可參考〈Module 模組化概念〉,並可與 ES5 做比較。










Related Posts

WEB 網路基礎概念

WEB 網路基礎概念

Jump Diffusion Option Valuation in  Discrete Time

Jump Diffusion Option Valuation in Discrete Time

First letter is capital

First letter is capital


Comments